package service

import (
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"github.com/robfig/cron"
	"service/basic/config"
	__ "service/basic/proto"
	"service/handler/model"
	"time"
)

// 预约信息添加
func (s *Server) Reservation(_ context.Context, in *__.ReservationReq) (*__.ReservationResp, error) {
	//添加事务
	tx := config.DB.Begin()
	//查找医生
	var docker model.Docker
	//添加预约信息
	reserv := model.Reservation{
		UserId:   uint(in.UserId),
		DockerId: uint(in.DockerId),
	}
	if err := reserv.Create(); err != nil {
		tx.Rollback() //事务回滚
		return nil, errors.New("预约信息失败")

	}
	docker.Id = uint(in.DockerId)
	if err := docker.GetDockerId(); err != nil {
		tx.Rollback() //事务回滚
		return nil, errors.New("医生信息查找失败")
	}
	////添加分布式锁
	//lockKey := fmt.Sprintf("lock_docker:%v", in.DockerId)
	//lockId := uuid.NewString()
	//err := config.Rdb.SetNX(config.Ctx, lockKey, lockId, time.Minute*5)
	//if err != nil {
	//	tx.Rollback() //事务回归
	//	return nil, errors.New("上锁失败")
	//}

	CornDockerId(in.DockerId)
	tx.Commit()
	return &__.ReservationResp{
		Id: int64(reserv.Id),
	}, nil
}

func CornDockerId(dockerId int64) {
	c := cron.New()
	spec := "* */5 * * * ?"
	err := c.AddFunc(spec, func() {
		lockKey := fmt.Sprintf("lock_docker:%v", dockerId)
		lockId := uuid.NewString()
		config.Rdb.Eval(config.Ctx, lockKey, []string{lockId}, time.Minute*5)

	})
	fmt.Println(err)
	c.Start()

	select {}
}
